package com.mid;

/**
 * Created by Lxk on 2020/1/12.
 */
public class Solution931 {

    public int minFallingPathSum(int[][] A) {
        int row = A.length, col = A.length;
        int[][] dp = new int[row][col];
        for (int i = 0; i < row; i++) {
            dp[0][i] = A[0][i];
        }
        for (int i = 1; i < row; i++) {
            for (int k = 0; k < col; k++) {
                if (k == 0) {
                    //i行第一个元素
                    int val = dp[i - 1][k] < dp[i - 1][k + 1] ? dp[i - 1][k] : dp[i - 1][k + 1];
                    dp[i][k] = val + A[i][k];
                } else if (Integer.valueOf(col - 1).equals(k)) {
                    //i行最后一个元素
                    int val = dp[i - 1][k - 1] < dp[i - 1][k] ? dp[i - 1][k - 1] : dp[i - 1][k];
                    dp[i][k] = val + A[i][k];
                } else {
                    //i行居中元素
                    int val = dp[i - 1][k - 1] < dp[i - 1][k] ? dp[i - 1][k - 1] : dp[i - 1][k];
                    val = val < dp[i - 1][k + 1] ? val : dp[i - 1][k + 1];
                    dp[i][k] = val + A[i][k];
                }
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < col; i++) {
            if (dp[row - 1][i] < min) {
                min = dp[row - 1][i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        int[][] matrix = {{51, 24}, {-50, 82}};
        Solution931 solution931 = new Solution931();
        System.out.println(solution931.minFallingPathSum(matrix));
    }

}
